/*
   This file is part of the 'Let's Do Stuff Together' project
   http://code.google.com/p/dostufftogether/

   Copyright 2010 Christoph Fuchs, Stefan Thaler

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.appspot.android2gather;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.appspot.android2gather.configuration.ServerConfiguration;
import com.appspot.android2gather.util.QueryHelper;

/**
 * TODO Describe this type briefly. If necessary include a longer description
 * and/or an example.
 * 
 * @author gigi
 * 
 */
public class LogonWebView extends Activity {

	/** Called when the activity is first created. */

	/**
	 * The WebView we use to log in and make our requests.
	 */
	public static WebView webview;
	Button backbutton;

	/**
	 * The HTML source of the last page the WebView finished loading.
	 */
	private static String lastHTML = "";

	public static String getLastHTML() {
		return lastHTML;
	}

	public static void setLastHTML(String lastHTML) {
		LogonWebView.lastHTML = lastHTML;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);

		webview = (WebView) findViewById(R.id.webview);

		Log.v("WebView", "Found web view: " + webview);

		backbutton = (Button) findViewById(R.id.button_webviewback);
		/*
		 * Set backbutton's onClick behavior to go to the main menu
		 */
		backbutton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.i("View", "Switching to main menu view");
				if (QueryHelper.isLoggedIn(webview.getContext())) {
					Intent mainMenuIntent = new Intent(getApplicationContext(),
							LetsDoStuff.class);
					startActivity(mainMenuIntent);
					setContentView(R.layout.main);					
				} else {
					Toast toast = new Toast(webview.getContext()).makeText(
							webview.getContext(), "Please authenticated!!!",
							Toast.LENGTH_SHORT);
					toast.show();
				}

			}
		});

		webview.setWebViewClient(new HelloWebViewClient());
		webview.getSettings().setJavaScriptEnabled(true);

		/* Register a new JavaScript interface called HTMLOUT */
		webview.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

		webview.loadUrl("http://" + ServerConfiguration.ACTIVITY_SERVER
				+ "/logon");		
	}
	
	
	

}

class HelloWebViewClient extends WebViewClient {
	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		// return true;
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.webkit.WebViewClient#onLoadResource(android.webkit.WebView,
	 * java.lang.String)
	 */
	@Override
	public void onLoadResource(WebView view, String url) {
		super.onLoadResource(view, url);
		// Toast toast = new
		// Toast(getApplicationContext()).makeText(getApplicationContext(),
		// System.currentTimeMillis()+" page loaded", Toast.LENGTH_SHORT);
		// toast.show();
		Log.v("WebView", "Loading url " + url);
		// String responseBody =
		// QueryHelper.queryServer(getApplicationContext(),
		// ServerConfiguration.GOOGLE_LOGIN_CHECK);
		// String responseBody =
		// QueryHelper.queryServer(getApplicationContext(), url);
		// Log.v("WebView", "Response body: " + responseBody);
		// if (responseBody != null && responseBody.equals("true")) {
		// Log.v("WebView", "AUTHENTICATED");
		// StringBuilder sb = new StringBuilder();
		// sb.append("<html>");
		// sb.append("<body>");
		// sb.append("<h3>Success!</h3>");
		// sb.append("<p>You have been authenticated using your Google openID. Please return to the application by pressing the back button on your android phone.</p>");
		// sb.append("</body>");
		// sb.append("</html>");
		// view.loadData(sb.toString(), "text/xml", "utf-8");
		// }
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.webkit.WebViewClient#onPageFinished(android.webkit.WebView,
	 * java.lang.String)
	 */
	@Override
	public void onPageFinished(final WebView view, String url) {
		super.onPageFinished(view, url);
		// This call inject JavaScript into the page which just finished
		// loading.
		LogonWebView.webview
				.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)
				&& LogonWebView.webview.canGoBack()) {
			LogonWebView.webview.goBack();
			return true;
		}
		return true;
		// return super.onKeyDown(keyCode, event);
	}
}

/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface {

	public void showHTML(String html) {
		Log.v("WebView", "GOT HTML: " + html);
		LogonWebView.setLastHTML(html);
		// Toast toast = new
		// Toast(webview.getContext()).makeText(webview.getContext(),
		// System.currentTimeMillis()+html, Toast.LENGTH_SHORT);
		// toast.show();
		if (html.contains("<head><head></head><body>true</body></head>")) {
			Log.v("WebView", "AUTHENTICATED");
			LetsDoStuff.isLoggedIn = true;

			/*
			 * Forward user to create activity view
			 */
			Log.i("View", "Switching to create activity view");
			Intent createActivityIntent = new Intent(
					LogonWebView.webview.getContext(), LetsDoStuff.class);
			LetsDoStuff.letsDoStuff.startActivity(createActivityIntent);
		}
	}
}
